// 当前排序方式
let currentSort = 'time';

// 初始化留言板
function initMessageBoard() {
    console.log('初始化留言板...');
    
    // 初始化 FilePond
    if (typeof FilePond !== 'undefined') {
        // 注册 FilePond 插件
        FilePond.registerPlugin(FilePondPluginImagePreview);
        FilePond.registerPlugin(FilePondPluginFileValidateType);
        
        // 初始化文件上传
        const inputElement = document.querySelector('#pond');
        if (inputElement) {
            const pond = FilePond.create(inputElement, {
                name: 'file',
                server: {
                    process: {
                        url: '/api/upload_image',
                        method: 'POST',
                        withCredentials: true,
                        headers: {
                            'Accept': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    }
                },
                labelIdle: '拖拽图片或点击上传',
                allowMultiple: true,
                maxFiles: 5,
                acceptedFileTypes: ['image/jpeg', 'image/png', 'image/gif']
            });

            // 存储上传的图片URL
            window.uploadedImages = new Map();

            // 文件上传成功事件
            pond.on('processfile', (error, file) => {
                if (!error && file.serverId) {
                    window.uploadedImages.set(file.id, file.serverId);
                }
            });

            // 文件移除事件
            pond.on('removefile', (error, file) => {
                if (!error) {
                    window.uploadedImages.delete(file.id);
                }
            });
        }
    }

    // 初始化表单提交
    const messageForm = document.getElementById('messageForm');
    if (messageForm) {
        messageForm.onsubmit = handleMessageSubmit;
    }

    // 初始化排序按钮
    document.querySelectorAll('[data-sort]').forEach(button => {
        button.onclick = handleSort;
    });

    // 加载初始留言列表
    loadMessages('time');
    document.querySelector('[data-sort="time"]').classList.add('bg-green-600', 'text-white');
}

// 处理留言提交
async function handleMessageSubmit(e) {
    e.preventDefault();
    const content = document.getElementById('messageContent').value.trim();
    
    if (!content) {
        alert('请输入留言内容');
        return;
    }

    try {
        const images = Array.from(window.uploadedImages.values());
        const response = await fetch('/api/message/create', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({ content, images })
        });
        
        const result = await response.json();
        if (result.code === 200) {
            document.getElementById('messageContent').value = '';
            const pond = document.querySelector('.filepond').FilePond;
            if (pond) {
                pond.removeFiles();
            }
            window.uploadedImages.clear();
            loadMessages(currentSort);
        } else {
            alert(result.msg || '发表失败');
        }
    } catch (error) {
        console.error('发表留言错误:', error);
        alert('发表失败，请重试');
    }
}

// 处理排序
function handleSort(e) {
    const sortBy = e.target.dataset.sort;
    currentSort = sortBy;
    document.querySelectorAll('[data-sort]').forEach(btn => {
        btn.classList.remove('bg-green-600', 'text-white');
    });
    e.target.classList.add('bg-green-600', 'text-white');
    loadMessages(sortBy);
}

// 加载留言列表
function loadMessages(sortBy = 'time') {
    fetch(`/api/message?sort=${sortBy}`)
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                const messageList = document.getElementById('messageList');
                messageList.innerHTML = '';
                result.data.forEach(message => {
                    const messageElement = renderMessage(message);
                    messageList.appendChild(messageElement);
                });
            } else {
                alert(result.msg || '加载失败');
            }
        })
        .catch(error => console.error('Error loading messages:', error));
}

// 渲染单条留言
function renderMessage(message) {
    const template = document.getElementById('messageTemplate');
    const clone = template.content.cloneNode(true);
    const messageCard = clone.querySelector('.message-card');
    
    messageCard.id = `message-${message.id}`;
    messageCard.querySelector('.user-avatar').src = message.avatar || '/static/images/default-avatar.png';
    messageCard.querySelector('.user-name').textContent = message.nickname || message.username;
    messageCard.querySelector('.created-time').textContent = message.created_time;
    messageCard.querySelector('.message-content').textContent = message.content;
    
    // 设置点赞状态
    const likeBtn = messageCard.querySelector('.like-btn');
    if (message.is_liked) {
        likeBtn.classList.add('text-green-600');
    }
    messageCard.querySelector('.like-count').textContent = message.like_count;
    
    // 渲染图片
    const gallery = messageCard.querySelector('.image-gallery');
    if (message.images && message.images.length > 0) {
        gallery.style.display = 'grid';
        message.images.forEach(url => {
            const img = document.createElement('img');
            img.src = getBaseUrl(url);
            img.className = 'w-full h-48 object-cover rounded-lg cursor-pointer';
            img.onclick = () => window.open(img.src, '_blank');
            gallery.appendChild(img);
        });
    } else {
        gallery.style.display = 'none';
    }
    
    // 渲染评论
    const commentsList = messageCard.querySelector('.comments-list');
    if (message.comments && message.comments.length > 0) {
        message.comments.forEach(comment => {
            const commentElement = renderComment(comment, message.id);
            commentsList.appendChild(commentElement);
        });
    }
    
    // 添加事件监听器
    messageCard.querySelector('.like-btn').onclick = () => toggleLike(message.id);
    const commentBtn = messageCard.querySelector('.comment-btn');
    const commentForm = messageCard.querySelector('.comment-form');
    
    commentBtn.onclick = () => {
        commentForm.classList.toggle('hidden');
        if (!commentForm.classList.contains('hidden')) {
            commentForm.querySelector('textarea').focus();
        }
    };
    
    const submitCommentBtn = messageCard.querySelector('.submit-comment');
    submitCommentBtn.onclick = () => {
        const content = commentForm.querySelector('textarea').value;
        submitComment(message.id, null, content);
    };
    
    return messageCard;
}

// 渲染评论
function renderComment(comment, messageId) {
    const div = document.createElement('div');
    div.className = 'bg-gray-50 rounded p-3 mb-3';
    div.innerHTML = `
        <div class="flex items-start space-x-2">
            <img src="${getBaseUrl(comment.avatar)}" 
                 class="w-8 h-8 rounded-full">
            <div class="flex-1">
                <div class="flex justify-between">
                    <span class="font-semibold">${comment.nickname || comment.username}</span>
                    <span class="text-gray-500 text-sm">${comment.created_time}</span>
                </div>
                <p class="text-sm mt-1">${comment.content}</p>
                <div class="mt-2 flex items-center space-x-2">
                    <button class="reply-btn text-gray-500 hover:text-green-600 text-sm">回复</button>
                </div>
                <div class="reply-form hidden mt-2">
                    <textarea class="w-full p-2 border rounded-lg text-sm" rows="2" 
                        placeholder="回复 ${comment.nickname || comment.username}..."></textarea>
                    <div class="text-right mt-2">
                        <button class="submit-reply bg-green-600 text-white px-4 py-1 rounded-lg text-sm hover:bg-green-700">
                            发表回复
                        </button>
                    </div>
                </div>
                <div class="replies-list pl-4 mt-2 space-y-2">
                    ${renderReplies(comment.replies)}
                </div>
            </div>
        </div>
    `;

    // 添加回复功能事件监听
    const replyBtn = div.querySelector('.reply-btn');
    const replyForm = div.querySelector('.reply-form');
    
    replyBtn.onclick = () => {
        replyForm.classList.toggle('hidden');
        if (!replyForm.classList.contains('hidden')) {
            replyForm.querySelector('textarea').focus();
        }
    };
    
    const submitReplyBtn = div.querySelector('.submit-reply');
    submitReplyBtn.onclick = () => {
        const content = replyForm.querySelector('textarea').value;
        submitComment(messageId, comment.id, content);
    };

    return div;
}

// 渲染回复
function renderReplies(replies) {
    if (!replies || replies.length === 0) return '';
    
    return replies.map(reply => `
        <div class="bg-gray-100 rounded p-2">
            <div class="flex items-start space-x-2">
                <img src="${getBaseUrl(reply.avatar)}" 
                     class="w-6 h-6 rounded-full">
                <div class="flex-1">
                    <div class="flex items-baseline space-x-1">
                        <span class="font-semibold text-sm">${reply.nickname || reply.username}</span>
                        <span class="text-gray-500 text-xs">回复</span>
                        <span class="font-semibold text-sm">${reply.parent_nickname || reply.parent_username}</span>
                    </div>
                    <p class="text-sm mt-1">${reply.content}</p>
                    <div class="mt-1">
                        <span class="text-gray-500 text-xs">${reply.created_time}</span>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

// 切换点赞状态
function toggleLike(messageId) {
    fetch(`/api/message/${messageId}/like`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(result => {
        if (result.code === 200) {
            const messageCard = document.querySelector(`#message-${messageId}`);
            const likeBtn = messageCard.querySelector('.like-btn');
            const likeCount = messageCard.querySelector('.like-count');
            likeCount.textContent = result.data.like_count;
            likeBtn.classList.toggle('text-green-600', result.data.is_liked);
        } else {
            alert(result.msg || '操作失败');
        }
    })
    .catch(error => console.error('Error toggling like:', error));
}

// 提交评论
function submitComment(messageId, parentId, content) {
    if (!content.trim()) {
        alert('请输入评论内容');
        return;
    }
    
    fetch(`/api/message/${messageId}/comment`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ content, parent_id: parentId })
    })
    .then(response => response.json())
    .then(result => {
        if (result.code === 200) {
            loadMessages(currentSort);
            const messageCard = document.querySelector(`#message-${messageId}`);
            const commentForm = messageCard.querySelector('.comment-form');
            commentForm.querySelector('textarea').value = '';
            commentForm.classList.add('hidden');
        } else {
            alert(result.msg || '评论失败');
        }
    })
    .catch(error => {
        console.error('Error submitting comment:', error);
        alert('评论失败，请重试');
    });
}

// 辅助函数：获取基础URL
function getBaseUrl(url) {
    if (!url) return '/static/images/default-avatar.png';
    const baseUrl = decodeURIComponent(url.split('?')[0]);
    return baseUrl.includes('%') ? decodeURIComponent(baseUrl) : baseUrl;
}

// 导出初始化函数
window.initMessageBoard = initMessageBoard; 